import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Tag,
  Badge,
  Divider,
  BackTop,
  // Icon,
  // Popconfirm,
  // message,
  // notification,
} from 'antd';
import StandardTableCustom from '../../customComponents/StandardTableCustom';
import OperateModal from './OperateModal';
import PageHeaderWrapperCustom from '../../customComponents/PageHeaderWrapperCustom';
import Ellipsis from '../../components/Ellipsis';

import styles from './List.less';

const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const status = [
  {
    key: -10000,
    badge: 'default',
    text: '不限',
    value: -10000,
  },
  {
    key: 2,
    badge: 'success',
    text: '已启用',
    value: 2,
  },
  {
    key: -2,
    badge: 'error',
    text: '已禁用',
    value: -2,
  },
];

@connect(({ customerLevel, loading }) => ({
  customerLevel,
  loading: loading.models.customerLevel,
}))
@Form.create()
class Standard extends PureComponent {
  state = {
    formValues: {},
    // addNewVisible:false,
    updateItemVisible: false,
    metaData: {},
    customData: {
      count: 0,
      list: [],
      pagination: {},
    },
    pageNo: 1,
    pageSize: 10,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { pageNo, pageSize } = this.state;
    dispatch({
      type: 'customerLevel/list',
      payload: { pageNo, pageSize },
    }).then(() => {
      const {
        customerLevel: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'customerLevel/list',
      payload: params,
    }).then(() => {
      const {
        customerLevel: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { pageSize } = this.state;

    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'customerLevel/list',
      payload: {
        pageNo: 1,
        pageSize,
      },
    }).then(() => {
      const {
        customerLevel: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  };

  handleEditClick = record => {
    this.setState({ metaData: record });
    this.setState({ updateItemVisible: true });
  };

  refreshGrid = pageNo => {
    const { dispatch } = this.props;
    const { customData } = this.state;
    const { pagination } = customData;

    const params = {
      pageNo: (pageNo || 1) <= 1 ? 1 : pageNo,
      pageSize: pagination.pageSize,
    };
    dispatch({
      type: 'customerLevel/list',
      payload: params,
    }).then(() => {
      const {
        customerLevel: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'customerLevel/list',
        payload: {
          ...values,
          pageNo: 1,
          pageSize,
        },
      }).then(() => {
        const {
          customerLevel: { data },
        } = this.props;
        this.setState({ customData: data });
      });
    });
  };

  // showAddNewModal = () => {
  //   this.setState({
  //     addNewVisible: true,
  //   });
  // };

  // afterAddNewModalOk = () => {
  //   this.setState({
  //     addNewVisible: false,
  //   });
  //   this.refreshGrid();
  // };

  // afterAddNewModalCancel = () => {
  //   this.setState({
  //     addNewVisible: false,
  //   });
  // };

  // afterUpdateItemModalOk = () => {
  //   this.setState({
  //     updateItemVisible: false,
  //   });
  //   const { customData } = this.state;
  //   const { pagination } = customData;
  //   const { current } = pagination;
  //   this.refreshGrid(current);
  // };

  // afterUpdateItemModalCancel = () => {
  //   this.setState({
  //     updateItemVisible: false,
  //   });
  // };

  // deleteItem = record => {
  //   const { dispatch } = this.props;

  //   dispatch({
  //     type: 'customerLevel/remove',
  //     payload: {
  //       customerLevelId: record.customerLevelId,
  //     },
  //   }).then(() => {
  //     const {
  //       customerLevel: { data },
  //     } = this.props;
  //     const { status: statusCode, message: messageText } = data;
  //     if (statusCode === 200) {
  //       notification.success({
  //         placement: 'bottomRight',
  //         message: '操作结果',
  //         description: '数据已经删除成功，请进行后续操作。',
  //       });

  //       const { customData } = this.state;
  //       const { pagination } = customData;
  //       const { current } = pagination;
  //       this.refreshGrid(current);
  //     } else {
  //       notification.error({
  //         placement: 'bottomRight',
  //         message: '操作结果',
  //         description: messageText,
  //       });
  //     }
  //   });
  // };

  // cancelDelete = () => {
  //   message.info('已取消删除操作。');
  // };

  renderSimpleForm() {
    const {
      form,
      // dispatch,
    } = this.props;
    const { getFieldDecorator } = form;
    // const {
    //   category,
    //   addNewVisible,
    // } = this.state;

    const statusOption = [];
    status.forEach(item => {
      const { text, value } = item;
      statusOption.push(
        <Select.Option key={value} value={value}>
          {text}
        </Select.Option>
      );
    });

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          <Col md={6} sm={24}>
            <FormItem label="关键词">
              {getFieldDecorator('keywords')(<Input placeholder="请输入需要搜索的内容" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status', {
                rules: [{ required: false, message: '请选择状态!' }],
                initialValue: status[0].value,
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {statusOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              {/* <Divider type="vertical" />
              <Button type="primary" onClick={this.showAddNewModal}>
                新增级别
              </Button>
              <OperateModal
                visible={addNewVisible}
                mode="add"
                category={category}
                dispatch={dispatch}
                afterOK={this.afterAddNewModalOk}
                afterCancel={this.afterAddNewModalCancel}
              /> */}
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { loading, dispatch } = this.props;
    const { customData, metaData, updateItemVisible, category } = this.state;
    const columns = [
      {
        title: 'Id',
        dataIndex: 'customerLevelId',
        width: 80,
        align: 'center',
      },
      {
        title: '名称',
        dataIndex: 'name',
        align: 'left',
        render: (val, record) => {
          const tag =
            record.type === 0 ? (
              <Tag color="#7a8aa2" style={{ marginLeft: '4px' }}>
                默认
              </Tag>
            ) : (
              ''
            );
          return (
            <Fragment>
              {val}
              {tag}
            </Fragment>
          );
        },
      },
      {
        title: '订货折扣',
        dataIndex: 'discount',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {`${val * 100}%`}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 120,
        align: 'center',
        filters: status,
        filterMultiple: false,
        onFilter: (value, record) => record.status.toString() === value,
        render(val, record) {
          let badgeValue = '';
          status.forEach(item => {
            const { badge, value } = item;
            if (value === val) {
              badgeValue = badge;
            }
          });
          return <Badge status={badgeValue} text={record.statusNote} />;
        },
      },
      // // 暂不开放编辑和删除功能
      // {
      //   title: '操作',
      //   width: 156,
      //   align: 'center',
      //   fixed: 'right',
      //   render: (text, record) => (
      //     <Fragment>
      //       <a onClick={() => this.handleEditClick(record)} className={styles.actionButton}>
      //         <Icon type="edit" className={styles.editButton} />编辑
      //       </a>
      //       <Popconfirm
      //         placement="topRight"
      //         title="此操作不会修改已有的商品信息，确定删除吗？"
      //         onConfirm={() => this.deleteItem(record)}
      //         onCancel={this.cancelDelete}
      //         okText="确定"
      //         cancelText="取消"
      //       >
      //         <a className={styles.actionButton}>
      //           <Icon type="delete" className={styles.editButton} />删除
      //         </a>
      //       </Popconfirm>
      //     </Fragment>
      //   ),
      // },
    ];

    return (
      <PageHeaderWrapperCustom title="渠道商级别列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTableCustom
              loading={loading}
              data={customData}
              columns={columns}
              expandedRowRender={record => (
                <div>
                  <p>
                    <span className="bold">名称：</span>
                    <span>{`${record.name}（ 订货折扣：${(record.discount || 1) * 100}% ）`}</span>
                  </p>
                  <Divider />
                  <p>
                    <span className="bold">其他信息：</span>
                    <span>{`创建于 ${record.createTime}，最后更新于 ${record.updateTime}。`}</span>
                  </p>
                </div>
              )}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <OperateModal
          visible={updateItemVisible}
          mode="update"
          metaData={metaData}
          category={category}
          dispatch={dispatch}
          afterOK={this.afterUpdateItemModalOk}
          afterCancel={this.afterUpdateItemModalCancel}
        />
        <BackTop />
      </PageHeaderWrapperCustom>
    );
  }
}

export default Standard;
